package com.cookpan001.mediators 
{
	import com.cookpan001.data.AppConst;
	import com.cookpan001.display.layer.BackLayer;
	import com.cookpan001.display.layer.StaticLayer;
	import com.cookpan001.proxies.DragProxy;
	import flash.display.DisplayObject;
	import flash.geom.Point;
	import org.puremvc.as3.interfaces.INotification;
	/**
	 * ...
	 * @author cookpan001
	 */
	public class StaticMediator extends AbstractMediator
	{
		public static const NAME:String = "StaticMediator";
		public function StaticMediator(view:Object) 
		{
			super(NAME,view);
		}
		
		public function get layer():StaticLayer
		{
			return viewComponent as StaticLayer;
		}
		
		//注册后启动
		override public function onRegister():void
		{
			super.onRegister();
			this.addLayer("BackLayer", new BackMediator(new BackLayer()));
		}
		
		//注册关心的消息
		override public function listNotificationInterests():Array
		{
			return [
				AppConst.START_DRAG,
				AppConst.DRAGGING,
				AppConst.END_DRAG
			];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			super.handleNotification(notification);
			var name:String = notification.getName();
			var offset:Point = notification.getBody() as Point;
			switch(name)
			{
				case AppConst.START_DRAG:
					this.startDrag(offset);
					break;
				case AppConst.DRAGGING:
					this.dragging(offset);
					break;
				case AppConst.END_DRAG:
					this.endDrag(offset);
					break;
				default:
					break;
			}
		}
		
		private function startDrag(offset:Point):void
		{
			if (facade.hasProxy(DragProxy.NAME))
			{
				var proxy:DragProxy = facade.retrieveProxy(DragProxy.NAME) as DragProxy;
				proxy.setData(offset);
			}
			else
			{
				facade.registerProxy(new DragProxy(offset));
			}
		}
		
		private function dragging(offset:Point):void
		{
			var proxy:DragProxy = facade.retrieveProxy(DragProxy.NAME) as DragProxy;
			var point:Point = proxy.getData() as Point;
			proxy.setData(offset);
			var tmp:Point = offset.subtract(point);
			tmp.x = this.layer.x + tmp.x;
			tmp.y = this.layer.y + tmp.y;
			var stageSize:Object = AppConst.stageSize;
			var minx:Number = Number(stageSize["width"] - this.layer.width);
			if (tmp.x <= 0 && tmp.x >= minx)
			{
				this.layer.x = tmp.x;
			}
			var miny:Number = Number(stageSize["height"] - this.layer.height);
			if (tmp.y <=0 && tmp.y >= miny)
			{
				this.layer.y = tmp.y;
			}
		}
		
		private function endDrag(offset:Point):void
		{
			var proxy:DragProxy = facade.retrieveProxy(DragProxy.NAME) as DragProxy;
			proxy.setData(offset);
		}
	}

}